function GSSOut = gs_nopoints(GSS)
%gs_nopoints - exclusion of points before strain calculation  
%
%       GSSOut = gs_nopoints(GSS)
%
% The input struct variable GSS is as in gs_dataload.
% This function shows the points and the correspondent arrows and permits 
% the exclusion of one or more points by magnification of correpondent
% errors.
% The field IncludedPoints, whose value is a logical vector, is added to 
% GSS, leading to GSSOut. In particular, npe = GSSOut.IncludedPoints is 
% such that [e(m) n(m)] is included if npe(m) is true and [e(m) n(m)] is 
% excluded if npe(m) is false instead.
% If the field IncludedPoints already exists in GSS, the points for which
% npei = GSS.IncludedPoints is false are considered to be already excluded. 
%
% See also GS_DATALOAD, GS_YEPOINTS, GRIDSTRAIN, STRAIN_ZERO.

% G. Teza, 2005, 2008, 2022.

format long e; 

ns = GSS.StationID;
stn = GSS.StationName; 
e = GSS.East;
n = GSS.North;
ve = GSS.EastVelocity;
vn = GSS.NorthVelocity;
IMS = GSS.RefImageStruct;
lv = length(e);

GSSfields = fields(GSS);
if ismember('IncludedPoints',GSSfields)
    npei = GSS.IncludedPoints;
    if ~islogical(npei)
        npei = logical(npei);
    end
else
    npei = [];
end

GSSOut = GSS;

%--- Included points: 
ei = e; 
ni = n;
vei = ve; 
vni = vn;
%--- Not included points:
ex  = nan(lv,1); 
nx  = nan(lv,1);
vex = nan(lv,1); 
vnx = nan(lv,1);

if ~isempty(npei)
    Iexcl = ~npei;                       % Not included points
    Inexcl = npei;                       % Included points (not excluded)
    if sum(Inexcl) <= 2
        helpdlg(...
            sprintf('%s\n%s','AT LEAST TWO POINTS MUST BE INCLUDED',...
            'NO EXCLUSION CAN BE OPERATED'),...
            'EXCLUSION INFO');
        GSS.IncludedPoints = npei;
        return
    end
    ei(Iexcl)  = NaN; 
    ni(Iexcl)  = NaN;
    vei(Iexcl) = NaN; 
    vni(Iexcl) = NaN;
    ex(Iexcl)  = e(Iexcl);  
    nx(Iexcl)  = n(Iexcl);
    vex(Iexcl) = ve(Iexcl); 
    vnx(Iexcl) = vn(Iexcl);
    npe = npei;
    if ~isempty(ns)
        nsi = ns; 
        nsi(Iexcl) = NaN;
        nsx = nan(lv,1); 
        nsx(Iexcl) = ns(Iexcl);
        stni = [];
        stnx = [];
    else
        nsi = []; 
        nsx = [];
        stni = stn;
        stnx = cell(lv,1);
    end
else
    npe = true(lv,1);
    if ~isempty(ns)
        nsi = ns; 
        nsx = nan(lv,1);
        stni = [];
        stnx = [];
    else
        nsi = []; 
        nsx = [];
        stni = stn;
        stnx = cell(lv,1);
    end
end

mediff = mean([std(diff(e)) std(diff(n))]);
  
nocont = 0;
nn = 1;
while nocont == 0
    if nn == 1
        %------------------------------------------------------------------
        figki = plotinette(ei,ni,vei,vni,ex,nx,vex,vnx,...
            nsi,nsx,stni,stnx,mediff,IMS,[]);
        %------------------------------------------------------------------
    else
%         figki = figure;
        set(figki,'Units','normalized','OuterPosition',[0 0 1 1]); 

    end
    nn = nn+1; 
    [x,y] = ginput(1);
    dist = sqrt((ei-x).^2+(ni-y).^2);
    [~,Imi] = min(dist);
    if length(Imi) > 1
        Imi = min(Imi); 
    end
    ep = ei(Imi);
    np = ni(Imi);
    hold on; 
    plot(ep,np,'xr','HandleVisibility','off'); 
    hold off;
    if isempty(ns)
        strPoint = stn{Imi};
    else
        strPoint = num2str(ns(Imi));
    end
    lb = uicontrol(figki,...
        'Style','listbox',...
        'string', {sprintf('EXCLUDE THE POINT %s (%f E, %f N)',strPoint,ep,np)...
            'DO NOT EXCLUDE THIS POINT'},...
        'FontSize',14,...
        'Units','normalized','Position', [0.05 0.05 0.40 0.15],...
        'Callback', 'uiresume(gcbf)');
    uiwait(figki);
    menuc = lb.Value;
    delete(lb);
    if menuc == 1
        ei(Imi) = NaN; 
        ni(Imi) = NaN;
        ex(Imi) = ep;  
        nx(Imi) = np;
        vei(Imi) = NaN;     
        vni(Imi) = NaN;
        vex(Imi) = ve(Imi); 
        vnx(Imi) = vn(Imi);
        npe(Imi) = false;
        if ~isempty(ns)
            nsi(Imi) = NaN; 
            nsx(Imi) = ns(Imi);
        else
            stni(Imi) = {[]}; %#ok<*AGROW>
            stnx(Imi) = stn(Imi); 
        end
        %------------------------------------------------------------------
        figki = plotinette(ei,ni,vei,vni,ex,nx,vex,vnx,...
            nsi,nsx,stni,stnx,mediff,IMS,figki.Number);
        %------------------------------------------------------------------
    end
    if sum(isnan(ei)) < lv-1  % In this case, at least a point could be excluded                                       % can be excluded
        lb = uicontrol(figki,...
            'Style','listbox',...
            'string', {'EXCLUDE ANOTHER POINT','SKIP'},...
            'FontSize',14,...
            'Units','normalized','Position', [0.05 0.05 0.30 0.15],...
            'Callback', 'uiresume(gcbf)');
        uiwait(figki);
        menud = lb.Value;
        delete(lb);
        if menud == 2
            nocont = 1; 
        end
    else
        nocont = 1;
    end
end

close(figki);

GSSOut.IncludedPoints = npe; 

%% ANCILLARY FUNCTIONS 

function figk = plotinette(ei,ni,vei,vni,ex,nx,vex,vnx,...
    nsi,nsx,stni,stnx,mediff,IMS,k)
% Plot of included points and related displacements (black color) and not 
% included points and displacements (red) on a figure with handle k.

Options = GridStrainOptions;

if ~isempty(k)
    figk = figure(k);
else
    figk = figure;
end
set(figk,'Units','normalized','OuterPosition',[0 0 1 1]); 
warning('off','all');

plot(ei,ni,'ok',ex,nx,'or');
legend('Point included','Point not included','Location','NorthEastOutside');
hold on
quiver(ei,ni,vei,vni,'k','HandleVisibility','off');   % vector visualization 
quiver(ex,nx,vex,vnx,'r','HandleVisibility','off');

if Options.VisualizePointIDs
    for kk = 1:numel(ei)
        if ~isempty(nsi) && ~isnan(nsi(kk))
            strikk = num2str(nsi(kk));
            okikk = true;
        elseif ~isempty(stni) && ~isempty(stni{kk})
            strikk = stni{kk};
            okikk = true;
        else
            okikk = false;
        end
        if okikk 
            se = sign(vei(kk)); 
            sn = sign(vni(kk));
            ht = text(ei(kk)-se*mediff/12,ni(kk)-sn*mediff/12,strikk);
            set(ht,'Color','b');
        end
    end
    for kk = 1:numel(ex)
        if ~isempty(nsx) && ~isnan(nsx(kk))
            strxkk = num2str(nsx(kk));
            okxkk = true;
        elseif ~isempty(stnx) && ~isempty(stnx{kk})
            strxkk = stnx{kk};
            okxkk = true;
        else
            okxkk = false;
        end
        if okxkk 
            se = sign(vex(kk)); sn = sign(vnx(kk));
            ht = text(ex(kk)-se*mediff/12,nx(kk)-sn*mediff/12,strxkk);
            set(ht,'Color','r');
        end
    end
end

title('CHOICE OF EXCLUDED POINTS','FontSize',14);
xlabel('EAST','FontSize',14); 
ylabel('NORTH','FontSize',14);
ALA = axis;
gs_ReadBGImage(IMS,ALA);
axis equal; 
hold off; 
set(gca,'FontSize',12);